package com.yylending.las.repay.repayrecord;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.airbnb.lottie.LottieAnimationView;
import com.yyfax.common.CLog;
import com.yyfax.common.recyclerview.adapter.CommonAdapter;
import com.yyfax.common.recyclerview.adapter.MultiItemTypeAdapter;
import com.yyfax.common.recyclerview.base.ViewHolder;
import com.yyfax.common.recyclerview.view.IRecyclerView;
import com.yyfax.common.recyclerview.wrapper.WrapperAdapter;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.main.MainActivity;
import com.yylending.las.repay.LoanDetailModel;
import com.yylending.las.repay.LoanDetailPresenter;
import com.yylending.las.repay.repaydetail.RepayDetailActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Pengrf on 2017/11/8.
 * Copyright  2017 www.yyfax.com. All Rights Reserved.
 */
public class NewRepaymentFragment extends BaseFragment implements View.OnClickListener, LoanDetailPresenter.View, MultiItemTypeAdapter.OnItemClickListener {
	private static final String TAG = NewRepaymentFragment.class.getSimpleName();
	/**
	 * 本月应还总额(元)/已逾期
	 */
	@BindView(R.id.repay_top_text)
	TextView mRepayTopText;
	/**
	 * 展示本月应还款/当前存在逾期,应还今个以实际通知为准
	 */
	@BindView(R.id.repay_middle_text)
	TextView mRepayMiddleText;
	/**
	 * 上半部分
	 */
	@BindView(R.id.repay_top_relativelayout)
	RelativeLayout mRepayTopRelativelayout;

	/**
	 * 客服电话
	 */
	@BindView(R.id.new_repayment_service_tv)
	TelephoneTextView mNewRepaymentServiceTv;
	/**
	 * 暂无借款
	 */
	@BindView(R.id.no_repay_ll)
	LinearLayout mNoRepayLl;
	@BindView(R.id.retry_tv)
	TextView mRetryTv;
	@BindView(R.id.retry_image)
	ImageView mRetryImage;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;
	@BindView(R.id.loading_view)
	LottieAnimationView mLoadingView;
	@BindView(R.id.message_tv)
	TextView mMessageTv;
	@BindView(R.id.page_loading_ll)
	LinearLayout mPageLoadingLl;
	@BindView(R.id.load_status_fl)
	FrameLayout mLoadStatusFl;
	Unbinder unbinder;

	@BindView(R.id.repayment_rv)
	IRecyclerView mRecyclerView;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	/**
	 * 顶端标题栏
	 */
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;

	private LoanDetailPresenter mLoanDetailPresenter;
	LoanDetailModel.LoanDetail loanDetail;    //静态?????

	private MultiItemTypeAdapter<LoanDetailModel.LoanDetail> mAdapter;
	private List<LoanDetailModel.LoanDetail> mRepaymentList = new ArrayList<>();

	public WrapperAdapter mWrapAdapter;

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case MainActivity.LOADER_ID_MY_LENDING:
				mLoanDetailPresenter = (LoanDetailPresenter) data;
				mLoanDetailPresenter.attach(this);
				mTitleTv.setText(R.string.tab_repay);        //加载中,标题栏展示 还款
				mPageLoadingLl.setVisibility(View.VISIBLE);
				mLoadStatusFl.setVisibility(View.VISIBLE);
				mLoadingView.playAnimation();

				mLoanDetailPresenter.getLoanDetail("", "", false);
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case MainActivity.LOADER_ID_MY_LENDING:
				return new PresenterLoader<>(getActivity(), new LoanDetailPresenter.Generator());
			default:
				return null;
		}
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_new_repayment, container, false);
		unbinder = ButterKnife.bind(this, rootView);
		initView();
		mNoNetworkLayout.setOnClickListener(this);
		return rootView;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}

	public static BaseFragment newInstance() {
		BaseFragment fragment = new NewRepaymentFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(MainActivity.LOADER_ID_MY_LENDING, null, this);
	}

	@Override
	public void onDetach() {
		getLoaderManager().destroyLoader(MainActivity.LOADER_ID_MY_LENDING);
		super.onDetach();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}

	/**
	 * 初始化数据
	 */
	private void initView() {
		mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));

		mAdapter = new CommonAdapter<LoanDetailModel.LoanDetail>(R.layout.adapter_item_repayment, mRepaymentList, mRecyclerView.getItemViewDelegateManager()) {
			@Override
			protected void convert(ViewHolder holder, LoanDetailModel.LoanDetail loanDetail, int position) {
				holder.setText(R.id.repay_amount_tv1, FormatUtils.getFormatMoney(loanDetail.repayAmount));    //本期应还
				long repayDate = TextUtils.isEmpty(loanDetail.repayDate) ? 0 : Long.valueOf(loanDetail.repayDate);//sometimes, repayDate == null
				holder.setText(R.id.repay_date_tv1, TimeUtils.formatDateTimeMonthSingleZh(repayDate));    //还款日期
				if(TextUtils.isEmpty(loanDetail.repayBank)){
					holder.setText(R.id.repay_card_tv1, getString(R.string.never_bind_bank_card));    //还款银行+还款卡号
				}else{
					holder.setText(R.id.repay_card_tv1, getString(R.string.repay_bank_card, loanDetail.repayBank, loanDetail.repayCard));    //还款银行+还款卡号
				}

				holder.setText(R.id.repay_loan_money_tv1, getString(R.string.loan_amount, FormatUtils.getDecoratedAmount(loanDetail.loanAmount)));    //借款数
				switch (loanDetail.repayStatus) {
					case LoanDetailPresenter.REPAY_STATUS_PAY_OFF: // TODO: 2017/11/14  已还清, 原型没有该状态, 后台接口有返回.

						break;
					case LoanDetailPresenter.REPAY_STATUS_HAS_PAY: // 本期已还
						holder.getView(R.id.isPaying_iv1).setVisibility(View.VISIBLE);
						break;
					case LoanDetailPresenter.REPAY_STATUS_OVERDUE: // 本期逾期
						holder.setText(R.id.repay_amount_tv1, getString(R.string.be_overdue));
						((TextView) holder.getView(R.id.repay_amount_tv1)).setTextColor(ContextCompat.getColor(getActivity(), R.color.color_ffff0000));

						holder.getView(R.id.isPaying_iv1).setVisibility(View.GONE);
						break;
					case LoanDetailPresenter.REPAY_STATUS_REPAY_PROCESSING: // 还款处理中
						((ImageView) holder.getView(R.id.isPaying_iv1)).setImageResource(R.drawable.ic_in_the_payment);
						break;
					case LoanDetailPresenter.REPAY_STATUS_TO_REPAY: // 本期待还
						holder.getView(R.id.isPaying_iv1).setVisibility(View.GONE);
						break;
					default:
						break;
				}
			}
		};
		mWrapAdapter = new WrapperAdapter(mAdapter, mRecyclerView, getActivity(), R.layout.no_loan_data, R.layout.include_view_no_network);
		mWrapAdapter.setOnItemClickListener(this);
		mRecyclerView.setAdapter(mWrapAdapter);
		mNewRepaymentServiceTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.no_network_layout:
				mLoanDetailPresenter.getLoanDetail("", "", false);
				mNoNetworkLayout.setVisibility(View.GONE);
				mPageLoadingLl.setVisibility(View.VISIBLE);
				mLoadStatusFl.setVisibility(View.VISIBLE);
				mLoadingView.playAnimation();
				break;
			default:
				break;
		}
	}

	@Override
	public void getLoanDetailSuccess(List<LoanDetailModel.LoanDetail> result) {
		mLoadStatusFl.setVisibility(View.GONE);
		mNoNetworkLayout.setVisibility(View.GONE);
		mPageLoadingLl.setVisibility(View.GONE);
		setData(result);
	}

	private void setData(List<LoanDetailModel.LoanDetail> result) {
		mLayoutTitleBar.setVisibility(View.GONE);
		mRecyclerView.stopRefreshing();
		mRepaymentList.clear();
		mRepaymentList.addAll(result);
		mWrapAdapter.refreshData(mRepaymentList);

		if (result.size() == 0) {
			mLayoutTitleBar.setVisibility(View.VISIBLE);
			mTitleTv.setText(R.string.tab_repay);
			mRepayTopRelativelayout.setVisibility(View.GONE);
			mNoRepayLl.setVisibility(View.VISIBLE);
			return;
		}

		//只要有逾期,不走下面赋值
		for (int i = 0; i < result.size(); i++) {
			if (LoanDetailPresenter.REPAY_STATUS_OVERDUE.equals(result.get(i).repayStatus)) {
				mRepayTopText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 38);
				mRepayTopText.setText(R.string.be_overdue);
				mRepayMiddleText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
				mRepayMiddleText.setText(R.string.repay_tips);
				return;
			}
		}

		// 判断是否全部还清
		boolean isPaidOff = true;
		for (int i = 0; i < result.size(); i++) {
			if (!LoanDetailPresenter.REPAY_STATUS_HAS_PAY.equals(result.get(i).repayStatus)) {
				isPaidOff = false;
				break;
			}
		}
		if(isPaidOff){
			mRepayMiddleText.setText(R.string.money_has_repay_of_this_term);
			return;
		}

		//遍历拿到每一笔当月应还,相加展示
		BigDecimal totalRepay = BigDecimal.ZERO;
		for (int i = 0; i < result.size(); i++) {
			if (!LoanDetailPresenter.REPAY_STATUS_HAS_PAY.equals(result.get(i).repayStatus) && !LoanDetailPresenter.REPAY_STATUS_PAY_OFF.equals(result.get(i).repayStatus)) {    //待还
				try {
					BigDecimal repaymentThisMonth = new BigDecimal(result.get(i).repayAmount);
					totalRepay = totalRepay.add(repaymentThisMonth);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
		}
		mRepayMiddleText.setText(FormatUtils.getFormatMoney(totalRepay));
	}


	@Override
	public void getLoanDetailFailed(String msg) {
		mLayoutTitleBar.setVisibility(View.VISIBLE);
		mLoadStatusFl.setVisibility(View.VISIBLE);
		mNoNetworkLayout.setVisibility(View.VISIBLE);
		mTitleTv.setText(R.string.tab_repay);
		mPageLoadingLl.setVisibility(View.GONE);

	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mLoadStatusFl.setVisibility(View.VISIBLE);
				mNoNetworkLayout.setVisibility(View.VISIBLE);
				mLayoutTitleBar.setVisibility(View.VISIBLE);
				mTitleTv.setText(R.string.tab_repay);
				mPageLoadingLl.setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 点击跳转还款详情
	 * 带借据号,类型type过去
	 *
	 * @param view
	 * @param holder
	 * @param position
	 * @param viewType
	 */
	@Override
	public void onItemClick(View view, ViewHolder holder, int position, int viewType) {
		StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_CHECK_REIMBURSEMENT_LIST, mRepaymentList.get(position - 1).repayStatus);
		RepayDetailActivity.start(getActivity(), mRepaymentList.get(position - 1).loanNo, "10");
	}

	@Override
	public boolean onItemLongClick(View view, ViewHolder holder, int position, int viewType) {
		return false;
	}
}
